package mostCommonWord;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        Set<String> bannedSet = new HashSet<>();
        Map<String,Integer> map = new HashMap<>();
        for (String s: banned) {
            bannedSet.add(getLower(s));
        }
        // 检查是不是单词
        int i = 0,j = 0,max = 0;
        String ans = "";
        while (i<paragraph.length()&&j<paragraph.length()) {
            if(!checkFirst(paragraph,i)) {
                i++;
                j = i;
            } else if (!checkLast(paragraph,j)) {
                j++;
            } else {
                String s = getLower(paragraph.substring(i,j+1));
                if(!bannedSet.contains(s)) {
                    int c = map.getOrDefault(s,0)+1;
                    if(max<c) {
                        ans = s;
                        max = c;
                    }
                    map.put(s,c);
                }
                i++;
            }
        }
        return ans;
    }
    private boolean checkFirst(String s,int i) {
        // 前一个不是字母 后一个是字母
        if(i == 0) return Character.isLetter(s.charAt(i));
        return (!Character.isLetter(s.charAt(i-1)))&&Character.isLetter(s.charAt(i));
    }
    private boolean checkLast(String s,int i) {
        if(i == s.length()-1) return Character.isLetter(s.charAt(i));
        return (!Character.isLetter(s.charAt(i+1)))&&Character.isLetter(s.charAt(i));
    }
    private String getLower(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            sb.append(Character.toLowerCase(s.charAt(i)));
        }
        return sb.toString();
    }
}
